
import Vue from 'vue';
import Router from 'vue-router';

import VueHtmlToPaper from 'vue-html-to-paper';

import App from './App.vue';
import store from './store';
import i18n from './config/i18n';
import axios from 'axios';

// // 引入自定义指令
// import directives from './directives';

import env from '@/config/env';

import routes from './routes';

import * as platform from '@cloudpivot/platform';


import './config/api';
import './config/antd';

import './styles/index.less';

let importReportService = false;

/**
 * 页面禁用拖拽上传时 浏览器默认打开图片
 */
document.addEventListener('drop', function (e) {
    e.preventDefault()
}, false)

document.addEventListener('dragover', function (e) {
    e.preventDefault()
}, false)


export async function startup(environment: any) {

    // 地址参数上携带access_token的，将token存在localstorage并清理地址上的参数
    if (environment && environment.access_token) {
        // 通过token获取refresh_token，实现token续期
        await axios.post(`${env.apiHost}/login/Authentication/get_refresh_token`, { access_token: environment.access_token }).then((res: any) => {
            if (res.errcode === 0 && res.data) {
                const refresh_tokens = (res as any).data.refresh_token;
                let expireTime = (res as any).data.expiration;

                // 时间戳如果为13位则单位是ms,把单位转为s
                if (expireTime.toString().length === 13) {
                    expireTime = expireTime.toString().slice(0, -3);
                }
        
                localStorage.setItem('refresh_token', refresh_tokens);
                localStorage.setItem('expireTime', expireTime);
            }
        });
        //打开表单详情时不清理access_token, 原因为 解决钉钉打开流程表单点击同意后不关闭页面问题
        if(!window.location.href.includes('/form/detail?')){
            const url = decodeURIComponent(window.location.href).replace('&access_token', 'access_token');
            window.location.href = url.replace(`access_token=${environment.access_token}`, '');   
        }
    }

    window.Environment = environment;
    window.Environment.isIe = /Trident/.test(navigator.userAgent);

    Vue.config.productionTip = false;
    Vue.use(Router);

    Vue.use(VueHtmlToPaper);

    // 单应用路由
    if (window.Environment.appCode) {
        ((routes[0]) as any).redirect = '/app-home';
    } else if (window.Environment.messageId) {
        // 消息路由
    }

    const router = new Router({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    });

    Vue.prototype.router = router;

    router.beforeEach((to: any, from: any, next: any) => {
        console.log(to,'totototototototototototototototototototototototo')

        let title = '奥哲云枢';
        if (to.meta && to.meta.title) {
            title = to.meta.title
        }
        platform.service.setTitle(title);
        if(to.name === 'appReport' && !importReportService){
            importReportService = true;
            import('@/views/applications/report-service');
        }
        if(to.name === 'applicationReport' && !importReportService){
            importReportService = true;
            import('@/views/applications/report-service');
        }

        if(to.name === 'applicationReport' && !importReportService){
            importReportService = true;
            import('@/views/applications/report-service');
        }
        // weiyaos
        let t_expireTime = localStorage.getItem('expireTime');

        // 用户userId=990012312(必传)  是否隐藏导航栏IsNavigation=true||false（没有传默认为true true为隐藏）  入口entrance=ERP||POS||XXX（必传）
        //userId返回来时
      console.log(8888,to)

        if (to.query.userId && to.query.entrance) {

          let IsNavigation = to.query.IsNavigation; //是否隐藏导航栏
            let userId = to.query.userId; //用户得userId
            let entrance = to.query.entrance //入口  ERP||POS (ERP系统需要根据参数隐藏左侧菜单栏表栏目)
            sessionStorage.setItem('IsNavigation', IsNavigation);

            let c_origin = location.origin;
            // c_origin= 'https://aozhe-pre.fastfish.com'
            const token = localStorage.getItem('token') ? localStorage.getItem('token') : '';

            let url = `${c_origin}/api/public/organization/signOn?userId=${userId}`
            axios.get(url).then((res: any) => {
                if (res.code == 0) {
                    if(res.data.errcode === 0){
                        localStorage.setItem('refresh_token', res.data.refresh_token);
                        localStorage.setItem('expireTime', res.data.expiration);
                        localStorage.setItem('token', res.data.access_token);
                        console.log('prePushnoTokenTo');
                        const refresh_token = localStorage.getItem('refresh_token');
                        const userInfoUrl = `${env.apiHost}/api/organization/user/info_login`;
                        axios.get(`${userInfoUrl}`, {
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                        }).then((res: any) => {
                            if (res.errcode === 0) {
                                const info: any = res.data;
                                sessionStorage.setItem('user', JSON.stringify(info));
                                next();
                                // console.log(`https://sso.avicnet.cn/sso/login?service=${encodeURIComponent(service)}`);
                                // window.location.replace(service);
                            }
                        })

                 

                        // axios.get(`https://aozhe-pre.fastfish.com/login/Authentication/get_refresh_token`, { params }).then((res: any) => {
                        //     // console.log(res);
                        //     if (res) {
                        //         const token = (res as any).access_token;
                        //         const refresh_tokens = (res as any).refresh_token;
                        //         const expireTime = (res as any).exp;
    
                        //         localStorage.setItem('refresh_token', refresh_tokens);
                        //         localStorage.setItem('expireTime', expireTime * 1000 + '');
                        //         localStorage.setItem('token', token);
                        //         const userInfoUrl = `${env.apiHost}/api/organization/user/info_login`;
                        //         axios.get(`${userInfoUrl}`, {
                        //             headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                        //         }).then((res: any) => {
                        //             if (res.errcode === 0) {
                        //                 const info: any = res.data;
                        //                 sessionStorage.setItem('user', JSON.stringify(info));
                        //                    next();
                        //                 // console.log(`https://sso.avicnet.cn/sso/login?service=${encodeURIComponent(service)}`);
                        //                 // window.location.replace(service);
                        //             }
                        //         })
                        //     }
                        // });

                    }

                } else {
                    console.log(' userId不存在')

                }
            });
            return;
        }
        // weiyaoe

        const token = localStorage.getItem('token');
        if (Vue.prototype.$httpRequestList.length > 0) {        //强行中断时才向下执行
            Vue.prototype.$httpRequestList.forEach((item:any)=>{
                item('interrupt');//给个标志，中断请求
            })  
        }
        if (env.enableProxy) {
            console.log(3333)
            next();

        } else {
            console.log(4444)
            // document.title = to.meta.title;
            if (!token && to.name !== 'login' && to.name !== 'oauth') {
                // alert(JSON.stringify(to));
                // window.location.href = '/login';
                next({ name: 'login' });
            } else {
                next();
            }
        }
    });

    // 全局注册自定义指令
    // Object.entries(directives).forEach((directive: any) => {
    //     const directiveName = directive[0];
    //     const directiveFunc = directive[1];
    //     Vue.directive(directiveName, directiveFunc);
    // });

    new Vue({
        router,
        i18n,
        store,
        render: (h: any) => h(App),
    }).$mount('#app');

}